package com.controller;

import com.dto.DemoDTO;
import com.utils.Pool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("demo")
public class DemoController {
    @Autowired
    private HttpServletRequest request;

    @PostMapping("login")
    public DemoDTO login(@RequestBody DemoDTO dto) {
        HttpSession session = request.getSession();
        session.setAttribute(Pool.SESSION_USER, dto);
        session.setMaxInactiveInterval(360);

        return dto;
    }

    @PostMapping("post")
    public DemoDTO post(@RequestBody DemoDTO dto) {
        return getAttribute(dto);
    }

    @GetMapping("get")
    public DemoDTO get(DemoDTO dto) {
        return getAttribute(dto);
    }

    @PutMapping("put")
    public DemoDTO put(DemoDTO dto) {
        return getAttribute(dto);
    }

    @DeleteMapping("delete")
    public DemoDTO delete(DemoDTO dto) {
        return getAttribute(dto);
    }

    private DemoDTO getAttribute(DemoDTO dto) {
        log.info(dto.toString());

        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(Pool.SESSION_USER);
        DemoDTO bean = null;
        if (attribute != null) {
            bean = (DemoDTO) attribute;
        }
        return bean;
    }
}
